package com.huang.leetcode.linkedList;

import com.huang.leetcode.constant.ListNode;

/**
 * @Author：CreateSequence
 * @Date：2020-07-26 14:45
 * @Description：合并两个有序链表
 * 题解：https://leetcode-cn.com/problems/merge-two-sorted-lists/solution/hua-jie-suan-fa-21-he-bing-liang-ge-you-xu-lian-bi/
 */
public class PB21 {

    /**
     * 递归解法
     * @param l1
     * @param l2
     * @return
     */
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }

        //比较l1和l2的大小
        //如果l1<l2，就接着判断l1.next < l2?，如果是，让l1.next = l1.next然后继续往下递归判断l1.next.next < l2 ?......反之亦然
        if (l1.val < l2.val) {
            l1.next = mergeTwoLists(l1.next, l2);
            return l1;
        }else {
            l2.next = mergeTwoLists(l1, l2.next);
            return l2;
        }
    }

    /**
     * 迭代解法
     * @param l1
     * @param l2
     * @return
     */
    public ListNode mergeTwoLists2(ListNode l1, ListNode l2) {
        ListNode pre = new ListNode(-1);
        ListNode cur = pre;
        //遍历直到一条链表到底
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                cur.next = l1;
                l1 = l1.next;
            }else {
                cur.next = l2;
                l2 = l2.next;
            }
            //指针前移
            cur = cur.next;
        }

        //判断哪一条链表到底了，直接接上另一条链表
        cur.next = l1 == null ? l2 : l1;
        return pre.next;
    }

}
